package voice;

import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

/**
 * Implements the voice message of the system
 * @author Alexandre, Cristovao, Raul, Rodolpho, Tales
 * @version 1.1
 * @milestone Number 2
 */
public class VoiceMessage {

	private TargetDataLine line;
	private AudioFileFormat.Type targetType;
	private AudioInputStream audioInputStream;
	private File outputFile;
	
	
	/**
	 * Constructor of the message
	 * @param msgId the id of the message
	 * @throws LineUnavailableException if the line is unavailable
	 */
	public VoiceMessage(VoiceMessageIdentification msgId) throws LineUnavailableException {
		//change the wave quality if want a smaller file
		AudioFormat audioFormat = new AudioFormat(
				AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F,
				false);
		DataLine.Info info = new DataLine.Info(TargetDataLine.class,
				audioFormat);
		TargetDataLine targetDataLine = null;
		targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
			targetDataLine.open(audioFormat);
		AudioFileFormat.Type type = AudioFileFormat.Type.WAVE;
	
		this.line = targetDataLine;
		this.audioInputStream = new AudioInputStream(line);
		this.targetType = type;
		//file name
		this.outputFile = new File(msgId.getFileName());
	}
	
	/**
	 * Start a record of new voice message 
	 */
	public void startRecording() {
		line.start();
		new Recorder(audioInputStream, targetType, outputFile).start();
	}
	
	/**
	 * Stop a recording of the voice message
	 */
	public void stopRecording() {
		line.stop();
		line.close();
	}

}
